//
//  HBPictureView.swift
//  sinaWeibo
//
//  Created by Beans on 16/6/27.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit
import SDWebImage

let PicViewMargin: CGFloat = 10
let PicItemMargin: CGFloat = 5
let PicItemWH = (UIScreen.mainScreen().bounds.width - 2 * PicViewMargin - 2 * PicItemMargin) / 3

let HBPictureViewReuseIdentifier = "HBPictureViewReuseIdentifier"

class HBPictureView: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate {

    var picURLs: [HBStatusPicViewModel]? {
        didSet {
            printLog(picURLs?.count)

            // 配图的宽高, 由图片数量决定
            let size = calculateSize()
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
            }
            // 赋值之后刷新数据
            reloadData()
        }
    }

    // 指定构造函数
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 添加及布局子控件
    private func setupUI() {
        backgroundColor = UIColor.whiteColor()

        dataSource = self
        delegate = self
        scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, -10, 0)

        // 注册
        self.registerClass(HBPictureCollectionViewCell.self, forCellWithReuseIdentifier: HBPictureViewReuseIdentifier)
        // 设置itemSize
        flowLayout.itemSize = CGSizeMake(PicItemWH, PicItemWH)
        flowLayout.minimumInteritemSpacing = PicItemMargin  // 左右
        flowLayout.minimumLineSpacing = PicItemMargin       // 上下
//        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, -PicViewMargin, 0)    // 错误, flowLayout针对item而言, 这里应该调整整个ImageView位置
    }

    // MARK: - UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs?.count ?? 0
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HBPictureViewReuseIdentifier, forIndexPath: indexPath) as! HBPictureCollectionViewCell      // 为什么接一个as!
        cell.viewModel = picURLs![indexPath.row]
        cell.backgroundColor = UIColor.cyanColor()

        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // MARK: - 发布通知
        // 多层采用通知; 把图片数组 以及 索引传递过去
        let userInfo: [String : AnyObject] = ["pic_urls" : picURLs!, "indexPath" : indexPath]
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationPhotoBrowser, object: self, userInfo: userInfo)
    }

    // MARK: - 计算整个图框宽高的方法
    private func calculateSize() -> CGSize {
        /** 图片大小的计算逻辑
        1. 1张图片 实际图片大小
        2. 4张图片 2*2
        3. 其他图片数量 1*3 2*2 3*3
        */
        guard let picCount = picURLs?.count else {
            return CGSizeZero
        }

        if picCount == 1 {
            /*
             设置图片大小的两种方式
             第一种: 等图片下载后, 根据图片大小返回size
             第二种: 后台返回图片大小, 设置好大小后, 异步下载图片 -- 瀑布流
            */

            // 从缓存里面取出图片(MD5)
            // 图片url
            let key = picURLs?.first?.model?.thumbnail_pic
            // 通过SD用图片url取图片
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)

            // 如果图片没有值, 返回默认宽高
            if image == nil {
                flowLayout.itemSize = CGSizeMake(PicItemWH, PicItemWH)
                return CGSizeMake(PicItemWH, PicItemWH)
            }

            // 针对图片太窄/太宽的处理
            var size = image.size
            if size.width < 80 {
                // 根据宽高比设置高度
                let width: CGFloat = 80
                let height = width / size.width * size.height
                size.width = width
                size.height = height > 150 ? 150 : height   // 约束最大高度
            } else if size.width > 200 {
                let width: CGFloat = 200
                let height = width / size.width * size.height
                size.width = width
                size.height = height > 200 ? 200 : height
            }

            flowLayout.itemSize = size  // 更改cell大小, 但多张图的也被改了
            return size   // 返回图片的大小 (collectionView的大小)

        } else {
            // 由于cell存在重用, 需要把上边改过的再恢复为原来的
            flowLayout.itemSize = CGSizeMake(PicItemWH, PicItemWH)
        }

        if picCount == 4 {
            return CGSizeMake(PicItemWH * 2 + PicItemMargin, PicItemWH * 2 + PicItemMargin)
        }

        // 其它数量, 固定配图宽度
        let row = (picCount - 1) / 3 + 1
        return CGSizeMake(UIScreen.mainScreen().bounds.width - 2 * PicViewMargin, (PicItemWH + PicItemMargin) * CGFloat(row))
    }
}


// MARK: - 自定义cell
class HBPictureCollectionViewCell: UICollectionViewCell {

    var viewModel: HBStatusPicViewModel? {
        didSet {
            iconImageView.sd_setImageWithURL(viewModel?.picURL)
        }
    }
    
    // 1. 指定构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 2. 添加剂布局子控件
    private func setupUI() {
        addSubview(iconImageView)

        iconImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.equalTo(self)
            make.top.bottom.equalTo(self)
        }
    }

    // 3. 懒加载
    private lazy var iconImageView: UIImageView = {
        let iconImageView = UIImageView()
        iconImageView.contentMode = .ScaleToFill    // 图片填充模式   // scaleAspectFill模式下有bug, 仍需完善
        return iconImageView
    }()
}
